package com.starxg.m3u8.parser;

import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

import lombok.Getter;
import lombok.Setter;

/**
 * M3U8
 *
 * @author huangxingguang@lvmama.com
 * @date 2020-08-11 11:20
 */
@Getter
@Setter
public abstract class M3U8 {
    static final String START_PREFIX = "#EXTM3U";
    static final String END_PREFIX = "#EXT-X-ENDLIST";

    /**
     * 源m3u8内容
     */
    private String raw;
    private URL url;
    private M3U8Key key;
    private String baseUrl;
    private String relativeUrl;

    public M3U8(URL url) {
        this.url = url;
    }

    public String getBaseUrl() {
        if (baseUrl != null) {
            return baseUrl;
        }
        return baseUrl = StringUtils.removeEnd(url.toString(), url.getPath());
    }

    public String getRelativeUrl() {
        if (relativeUrl != null) {
            return relativeUrl;
        }
        return relativeUrl = FilenameUtils.getFullPath(url.toString());
    }

    public URL absUrl(String uri) throws MalformedURLException {
        // 如果不是 http https 开头那就要加前缀
        if (!(uri.startsWith("http") || uri.startsWith("https"))) {
            if (uri.startsWith("/")) {
                uri = getBaseUrl() + uri;
            } else {
                uri = getRelativeUrl() + uri;
            }
        }
        return new URL(uri);
    }
}
